package com.example.oauth2.util;

import org.apache.commons.lang.SerializationUtils;

import javax.persistence.AttributeConverter;

/**
 * 属性转换器
 * 作用：插入数据库时，把对象转为字符串，查询数据时，字符串转为实体对象
 */
public class ObjectToBytesAttributeConverter implements AttributeConverter<Object, byte[]> {

    @Override
    public byte[] convertToDatabaseColumn(Object o) {

        SerializationWrapper serializationWrapper = new SerializationWrapper(o);
        return SerializationUtils.serialize(serializationWrapper);
    }

    @Override
    public Object convertToEntityAttribute(byte[] bytes) {

        SerializationWrapper serializationWrapper = (SerializationWrapper) SerializationUtils.deserialize(bytes);
        return serializationWrapper.getWrapObject();
    }
}
